#include "FileLoader.h"

CFileLoader::CFileLoader(void)
: m_pFile(NULL)
{
	m_uFileSize = 0;
	m_uPos = 0;
}

CFileLoader::~CFileLoader(void)
{
	close();
}

//! Open a file with the specify mode
bool CFileLoader::open(const char* pszFile, const char* mode)
{
	m_strFileName = pszFile;
	
	this->close();
	//m_pFile = fopen(pszFile, mode);
	//MSDN said fopen is unsafe , so change for fopen_s
	if(0 != fopen_s(&m_pFile, pszFile, mode))
		return false;

	fseek(m_pFile, 0, SEEK_END);
	m_uFileSize = ftell(m_pFile);
	fseek(m_pFile, 0, SEEK_SET);

	return true;
}

//! Read data from file
u32	CFileLoader::readData(void* pDst, u32 readsize)
{
	if(!m_pFile)
		return 0;
	
	return fread(pDst, 1, readsize, m_pFile);
}

//! write data to file
u32 CFileLoader::writeData(void* pSrc, u32 size)
{
	if(!m_pFile)
		return 0;

	return fwrite(pSrc, 1, size, m_pFile);
}

//! close the file
void CFileLoader::close()
{
	if(NULL != m_pFile)
	{
		fclose(m_pFile);
		m_pFile = NULL;
	}
}

//! whether the file is open 
bool CFileLoader::isOpen()
{
	return m_pFile != NULL;
}

//! Forward pos form now position
void CFileLoader::forwardFilePos(u32 pos)
{
	if(!isOpen())
		return;
	
	u32 now = ftell(m_pFile);
	u32 real = pos;
	if(now + pos > m_uFileSize)
		real = m_uFileSize-now;

	fseek(m_pFile, real, SEEK_CUR);
}

//! Backward pos from now position
void CFileLoader::backwardFilePos(u32 pos)
{
	if(!isOpen())
		return;

	u32 now = ftell(m_pFile);
	u32 real = now - pos;
	if(real < 0)
		real = 0;
	
	fseek(m_pFile, real, SEEK_SET);
}

//! Set file pointer to pos from begin
void CFileLoader::setFilePos(u32 pos)
{
	if(!isOpen())
		return;
	u32 real = pos;
	if(pos > m_uFileSize)
		real = m_uFileSize;
	
	fseek(m_pFile, real, SEEK_SET);
}